package cn.javasea.rbac.shiro.realm;

import cn.javasea.rbac.shiro.domain.Permission;
import cn.javasea.rbac.shiro.domain.Role;
import cn.javasea.rbac.shiro.domain.User;
import cn.javasea.rbac.shiro.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

/**
 *@ClassName CustomRealm
 *@Description TODO
 *@Author longxiaonan@163.com
 *@Date 2021/7/6 0006 10:06
 */
public class CustomRealm extends AuthorizingRealm {

    @Override
    public void setName(String name){
        super.setName("customRealm");
    }

    @Autowired
    private UserService userService;

    /**
     * 授权方法
     *      判断用户是否具有相应的权限
     *          先认证，再授权。
     *          doGetAuthenticationInfo 返回了安全数据，在这里通过安全数据获取用户具有的所有权限
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 1.获取已认证的用户数据
        User user = (User)principalCollection.getPrimaryPrincipal();
        // 2.根据用户认证数据拿所有权限信息(所有角色，所有权限)
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Set<String> roles = new HashSet<>();
        Set<String> perms = new HashSet<>();
        for(Role role : user.getRoles()){
            roles.add(role.getName());
            for(Permission perm : role.getPermissions()){
                perms.add(perm.getCode());
            }
        }
        info.setStringPermissions(perms);
        info.setRoles(roles);
        return info;
    }

    /**
     * 认证方法
     * @param authenticationToken subject.login 传递的用户名和密码
     * @return
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 1.获取登陆的用户名密码（token中）
        UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;
        String username = token.getUsername();
        String password = new String(token.getPassword());
        // 2.根据用户名查询数据库
        User user = userService.findByName(username);
        // 3.判断用户是否存在或密码是否一致
        if(Objects.nonNull(user) && user.getPassword().equals(password)){
            // 4.如果一致返回安全数据
            // 参数：1.安全数据，2.密码，realm域名(类中已经设置，直接取即可)
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName());
            return info;
        }
        // 5.不一致，返回null（抛出异常）
        return null;
    }
}
